package com.easylinkin.linkappapi.openapi.util;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.openapi.dto.SystemDocking;
import com.easylinkin.linkappapi.openapi.dto.systemDock.ResultDTO;
import com.easylinkin.linkappapi.openapi.dto.systemDock.TokenDTO;
import com.easylinkin.linkappapi.openapi.mapper.SystemDockingMapper;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 东西湖智慧监管平台
 * 定时更新token属性。
 */
@Component
public class TokenRefreshTimeer {

    private static final Logger logger = LoggerFactory.getLogger(TokenRefreshTimeer.class);

    @Resource
    private SystemDockingMapper systemDockingMapper;

    //每小时执行执行一次
    @Scheduled(cron = "0 0 */1 * * ?")
    public void refreshToken() throws IOException {

        try {
            logger.info("启动定时刷新token任务 TokenRefreshTimeer-----start");

            QueryWrapper<SystemDocking> qw = new QueryWrapper<>();
            //固定吧。
            qw.eq("sys_name", "临空港安全文明智慧监管平台");
            List<SystemDocking> list = systemDockingMapper.selectList(qw);

            if (list != null && list.size() > 0) {

                SystemDocking docking = list.get(0);
                //获取token
                String token = docking.getToken();
                String refreshToken = docking.getRefreshToken();
                String url = docking.getUrl() + "/assessHardware/client/login";

                Map<String, Object> map = new HashMap<>();
                map.put("appKey", docking.getAppid());
                map.put("appSecret", MD5Util.getMD5(docking.getSecret()));

                String response = "";
                //令牌为空重新登录获取
                if (StringUtils.isBlank(token) || StringUtils.isBlank(refreshToken)) {
                    response = HttpClientUtil.doPost(url, JSONObject.toJSONString(map));
                    logger.info(response);
                } else {
                    url = docking.getUrl() + "/assessHardware/client/refreshLogin";
                    //令牌信息不为空调用刷新token接口
                    map.put("refreshToken", docking.getRefreshToken());
                    response = HttpClientUtil.doPost(url, JSONObject.toJSONString(map));
                    logger.info("刷新token" + response);
                    ResultDTO responseDto = new Gson().fromJson(response, ResultDTO.class);
                    if (responseDto.getStatus() != 200) {
                        //token已过期，令牌过期，无法刷新，重新登录
                        url = docking.getUrl() + "/assessHardware/client/login";
                        response = HttpClientUtil.doPost(url, JSONObject.toJSONString(map));
                        logger.info("重新登录获取token");
                    }
                }

                ResultDTO responseDto = new Gson().fromJson(response, ResultDTO.class);
                //请求成功
                if (responseDto.getStatus() == 200) {
                    TokenDTO tokenDTO = new Gson().fromJson(responseDto.getData().toString(), TokenDTO.class);
                    System.out.println(tokenDTO.getToken() + "-------");
                    docking.setToken(tokenDTO.getToken());
                    docking.setRefreshToken(tokenDTO.getRefreshToken());
                    systemDockingMapper.updateById(docking);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
